package me.zhengjie.business.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.nmi.ChsInterfaceConfig;
import me.zhengjie.utils.HttpClientUtils;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 李迎华
 * @Date: 2021/7/29 15:58
 * @Description: 请求接口方法
 */
@Slf4j
@Service
public class HttpNewMicProvince {
/*

    @Autowired
    private ChsInterfaceLogService chsInterfaceLogService;
*/

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 获取token
     **/
    public String getToken(DeptDto deptDto) {
        Map<String, String> parmap = new HashMap<String, String>();
        parmap.put("username", deptDto.getProvinceClientName());
        parmap.put("password", deptDto.getProvinceClientPassword());
        parmap.put("scope", ChsInterfaceConfig.scopeServer);
        parmap.put("grant_type", ChsInterfaceConfig.grantTypePassword);
        Map<String, String> headermap = new HashMap<String, String>();
        headermap.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((deptDto.getProvinceClientId() + ":" + deptDto.getProvinceClientSecret()).getBytes(StandardCharsets.UTF_8)));
        headermap.put("Content-Type", "application/x-www-form-urlencoded");

        // System.out.println("parmap:"+parmap);
        // System.out.println("headermap:"+headermap);
        String result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.tokenUrl, parmap, headermap, Charset.forName("UTF-8"), null);

        // System.out.println("result:"+result);

        if (!"".equals(result)) {
            JSONObject json = JSONObject.parseObject(result);
            //有code为错误情况
            if (json.getString("code") == null) {
                //CacheUtils.put(deptDto.getProvinceClientName() + "NewMicToken", result);
                redisUtils.set(deptDto.getProvinceClientName() + "NewMicToken", result);
            }
        } else {
            result = "{err_msg: '获取token失败,机构信息有误或未进入省平台', code: 500}";
        }
        return result;
    }

    /**
     * 接口调用
     *
     * @param message 入参
     */
    public String handle(String message, DeptDto deptDto) {

        Map<String, String> headermap = new HashMap<String, String>();

        String token = String.valueOf(redisUtils.get(deptDto.getProvinceClientName() + "NewMicToken"));
        if (StringUtils.isEmpty(token) || "null".equals(token)) {
            token = getToken(deptDto);
            JSONObject json = JSONObject.parseObject(token);
            //code 不为空 报错
            if (json.getString("code") != null) {
                return token;
            }
        }
        JSONObject tokenJ = JSONObject.parseObject(token);
        headermap.put("Authorization", "Bearer " + tokenJ.getString("access_token"));
        headermap.put("Content-Type", "application/json;charset=utf8");
        String result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.serverUrl, null, headermap, Charset.forName("UTF-8"), message);
        if (result != null) {
            JSONObject jsonR = JSONObject.parseObject(result);
            if (!"".equals(jsonR.getString("error")) && "invalid_token".equals(jsonR.getString("error"))) {
                //token 失效
                token = getToken(deptDto);
                JSONObject newToken = JSONObject.parseObject(token);

                headermap.put("Authorization", "Bearer " + newToken.getString("access_token"));
                headermap.put("Content-Type", "application/json;charset=utf8");
                result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.serverUrl, null, headermap, Charset.forName("UTF-8"), message);
                JSONObject jrR = JSONObject.parseObject(result);
                if (!"".equals(jrR.getString("error")) && "invalid_token".equals(jrR.getString("error"))) {
                    redisUtils.del(deptDto.getProvinceClientName() + "NewMicToken");
                    throw new RuntimeException("token已失效请重新操作,或检查公共平台token失效时间是否小于2");
                }
            }
        } else {
            JSONObject json = new JSONObject();
            json.put("infcode", "-1");
            json.put("err_msg", "链接医保网络失败,请重试或联系管理员");
            result = json.toString();
        }
        return result;
    }

    /**
     * 接口调用 存日志
     *
     * @param message 入参
     * @param title
     */
    public String handle(String message, String title, DeptDto deptDto) {
        Map<String, String> headermap = new HashMap<String, String>();
        String token = String.valueOf(redisUtils.get(deptDto.getProvinceClientName() + "NewMicToken"));
        if (StringUtils.isEmpty(token) || "null".equals(token)) {
            token = getToken(deptDto);
            JSONObject json = JSONObject.parseObject(token);
            //code 不为空 报错
            if (json.getString("code") != null) {
                return token;
            }
        }
        JSONObject tokenJ = JSONObject.parseObject(token);
        headermap.put("Authorization", "Bearer " + tokenJ.getString("access_token"));
        headermap.put("Content-Type", "application/json;charset=utf8");
        String result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.serverUrl, null, headermap, Charset.forName("UTF-8"), message);
        if (result != null) {
            JSONObject jsonR = JSONObject.parseObject(result);
            if (!"".equals(jsonR.getString("error")) && "invalid_token".equals(jsonR.getString("error"))) {
                //第一次 token 失效 重新请求token
                token = getToken(deptDto);
                // log.info("第一次 token 失效 重新请求token: {} ", token);
                JSONObject newToken = JSONObject.parseObject(token);
                headermap.put("Authorization", "Bearer " + newToken.getString("access_token"));
                headermap.put("Content-Type", "application/json;charset=utf8");
                result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.serverUrl, null, headermap, Charset.forName("UTF-8"), message);
                //再次检测token失效
                JSONObject jrR = JSONObject.parseObject(result);
                if (!"".equals(jrR.getString("error")) && "invalid_token".equals(jrR.getString("error"))) {
                    //CacheUtils.remove(deptDto.getProvinceClientName() + "NewMicToken");
                    redisUtils.del(deptDto.getProvinceClientName() + "NewMicToken");
                    throw new RuntimeException("token已失效请重新操作,或检查公共平台token失效时间是否小于2");
                }

            }
/*            SysUser user = ShiroUtils.getSysUser();
            ChsInterfaceLog chsInterfaceLog = new ChsInterfaceLog();
            chsInterfaceLog.setTitle(title);
            chsInterfaceLog.setInput(message);
            chsInterfaceLog.setOutput(result);
            chsInterfaceLog.setOperName(user.getUserName());
            chsInterfaceLog.setDeptName(user.getDept().getDeptName());
            chsInterfaceLog.setClientId(dept.getProvinceClientId());
            chsInterfaceLog.setOperTime(new Date());
            chsInterfaceLogService.insertChsInterfaceLog(chsInterfaceLog);*/
        } else {
            JSONObject json = new JSONObject();
            json.put("infcode", "-1");
            json.put("err_msg", "链接医保网络失败,请重试或联系管理员");
            result = json.toString();
        }
        return result;
    }


    /**
     * 接口调用 存日志
     *
     * @param message 入参
     * @param title
     */
    public String handle9101(String message, String title, DeptDto deptDto) {
        Map<String, String> headermap = new HashMap<String, String>();
        String token = String.valueOf(redisUtils.get(deptDto.getProvinceClientName() + "NewMicToken"));
        if (StringUtils.isEmpty(token) || "null".equals(token)) {
            token = getToken(deptDto);
            // System.out.println(token);
            JSONObject json = JSONObject.parseObject(token);
            //code 不为空 报错
            if (json.getString("code") != null) {
                return token;
            }
        }
        JSONObject tokenJ = JSONObject.parseObject(token);
        headermap.put("Authorization", "Bearer " + tokenJ.getString("access_token"));
        headermap.put("Content-Type", "application/json;charset=utf8");
        String result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.fileUrl, null, headermap, Charset.forName("UTF-8"), message);
        if (result != null) {
            JSONObject jsonR = JSONObject.parseObject(result);
            if (!"".equals(jsonR.getString("error")) && "invalid_token".equals(jsonR.getString("error"))) {
                //第一次 token 失效 重新请求token
                token = getToken(deptDto);
                JSONObject newToken = JSONObject.parseObject(token);
                headermap.put("Authorization", "Bearer " + newToken.getString("access_token"));
                headermap.put("Content-Type", "application/json;charset=utf8");
                result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.fileUrl, null, headermap, Charset.forName("UTF-8"), message);
                //再次检测token失效
                JSONObject jrR = JSONObject.parseObject(result);
                if (!"".equals(jrR.getString("error")) && "invalid_token".equals(jrR.getString("error"))) {
                    //CacheUtils.remove(deptDto.getProvinceClientName() + "NewMicToken");
                    redisUtils.del(deptDto.getProvinceClientName() + "NewMicToken");
                    throw new RuntimeException("token已失效请重新操作,或检查公共平台token失效时间是否小于2");
                }

            }
/*            SysUser user = ShiroUtils.getSysUser();
            ChsInterfaceLog chsInterfaceLog = new ChsInterfaceLog();
            chsInterfaceLog.setTitle(title);
            chsInterfaceLog.setInput(message);
            chsInterfaceLog.setOutput(result);
            chsInterfaceLog.setOperName(user.getUserName());
            chsInterfaceLog.setDeptName(user.getDept().getDeptName());
            chsInterfaceLog.setClientId(dept.getProvinceClientId());
            chsInterfaceLog.setOperTime(new Date());
            chsInterfaceLogService.insertChsInterfaceLog(chsInterfaceLog);*/
        } else {
            JSONObject json = new JSONObject();
            json.put("infcode", "-1");
            json.put("err_msg", "链接医保网络失败,请重试或联系管理员");
            result = json.toString();
        }
        return result;
    }


    /**
     * 接口调用 存日志
     *
     * @param encryption_message 入参
     * @param normal_message 入参
     * @param title
     */

    public String handle(String encryption_message, String normal_message, String title, DeptDto deptDto) {
        Map<String, String> headermap = new HashMap<String, String>();
        String token = String.valueOf(redisUtils.get(deptDto.getProvinceClientName() + "NewMicToken"));
        if (StringUtils.isEmpty(token) || "null".equals(token)) {
            token = getToken(deptDto);
            // System.out.println(token);
            JSONObject json = JSONObject.parseObject(token);
            //code 不为空 报错
            if (json.getString("code") != null) {
                return token;
            }
        }
        JSONObject tokenJ = JSONObject.parseObject(token);
        headermap.put("Authorization", "Bearer " + tokenJ.getString("access_token"));
        headermap.put("Content-Type", "application/json;charset=utf8");
        String result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.serverUrl, null, headermap, Charset.forName("UTF-8"), encryption_message);
        String output = "";
        if (result != null) {
            JSONObject jsonR = JSONObject.parseObject(result);
            // System.out.println("jsonR:"+jsonR);
            output = jsonR.getString("output");
            if (!"".equals(jsonR.getString("error")) && "invalid_token".equals(jsonR.getString("error"))) {
                //第一次 token 失效 重新请求token
                token = getToken(deptDto);
                JSONObject newToken = JSONObject.parseObject(token);
                headermap.put("Authorization", "Bearer " + newToken.getString("access_token"));
                headermap.put("Content-Type", "application/json;charset=utf8");
                result = HttpClientUtils.sendIOPost(ChsInterfaceConfig.serverUrl, null, headermap, Charset.forName("UTF-8"), encryption_message);
                //再次检测token失效
                JSONObject jrR = JSONObject.parseObject(result);
                // System.out.println("jrR:"+jrR);
                if (!"".equals(jrR.getString("error")) && "invalid_token".equals(jrR.getString("error"))) {
                    //CacheUtils.remove(deptDto.getProvinceClientName() + "NewMicToken");
                    redisUtils.del(deptDto.getProvinceClientName() + "NewMicToken");
                    throw new RuntimeException("token已失效请重新操作,或检查公共平台token失效时间是否小于2");
                }

                output = jrR.getString("output");
                // System.out.println("output:"+output);
            }
/*            SysUser user = ShiroUtils.getSysUser();
            ChsInterfaceLog chsInterfaceLog = new ChsInterfaceLog();
            chsInterfaceLog.setTitle(title);
            chsInterfaceLog.setInput(normal_message);
            chsInterfaceLog.setOutput(SmUtil.decryption(output));
            chsInterfaceLog.setOperName(user.getUserName());
            chsInterfaceLog.setDeptName(user.getDept().getDeptName());
            chsInterfaceLog.setClientId(dept.getProvinceClientId());
            chsInterfaceLog.setOperTime(new Date());
            chsInterfaceLogService.insertChsInterfaceLog(chsInterfaceLog);*/
        } else {
            JSONObject json = new JSONObject();
            json.put("infcode", "-1");
            json.put("err_msg", "链接医保网络失败,请重试或联系管理员");
            result = json.toString();
        }
        return result;
    }

/*

    public String downFile(String message, String title, DeptDto deptDto) {
        Map<String, String> headermap = new HashMap<String, String>();
        String token = String.valueOf(CacheUtils.get(deptDto.getProvinceClientName() + "NewMicToken", 0));
        if ("0".equals(token)) {
            token = getToken(deptDto);
            JSONObject json = JSONObject.parseObject(token);
            //code 不为空 报错
            if (json.getString("code") != null) {
                return token;
            }
        }
        JSONObject tokenJ = JSONObject.parseObject(token);
        headermap.put("Authorization", "Bearer " + tokenJ.getString("access_token"));
        headermap.put("Content-Type", "text/plain");
        String result = HttpClientUtils.downFile(ChsInterfaceConfig.fileUrl, null, headermap, Charset.forName("UTF-8"), message, title);
        if (result != null) {
            JSONObject jsonR = JSONObject.parseObject(result);
            if (!"".equals(jsonR.getString("error")) && "invalid_token".equals(jsonR.getString("error"))) {
                //token 失效
                token = getToken(deptDto);
                JSONObject newToken = JSONObject.parseObject(token);
                if (newToken.getString("code") == null || "500".equals(newToken.getString("code"))) {
                    CacheUtils.remove(deptDto.getProvinceClientName() + "NewMicToken");
                    return token;
                } else {
                    headermap.put("Authorization", "Bearer " + newToken.getString("access_token"));
                    headermap.put("Content-Type", "text/plain");
                    result = HttpClientUtils.downFile(ChsInterfaceConfig.fileUrl, null, headermap, Charset.forName("UTF-8"), message, title);
                }
            }
        } else {
            JSONObject json = new JSONObject();
            json.put("infcode", "0");
            json.put("output", "");
            result = json.toString();
        }
*/
/*
        SysUser user = ShiroUtils.getSysUser();
        ChsInterfaceLog chsInterfaceLog = new ChsInterfaceLog();
        chsInterfaceLog.setTitle("文件下载");
        chsInterfaceLog.setInput(message);
        chsInterfaceLog.setOutput(result);
        chsInterfaceLog.setOperName(user.getUserName());
        chsInterfaceLog.setDeptName(user.getDept().getDeptName());
        chsInterfaceLog.setOperTime(new Date());
        chsInterfaceLogService.insertChsInterfaceLog(chsInterfaceLog);*//*

        return result;
    }
*/

}


